﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;
using ClinicManagement.Print;
using GeneralLibs;
using ReportGenerators._1Clinic;
using CustomSecurity;
using System.Collections;

namespace ReportGenerators._1Clinic
{
    public partial class FrmBangKeThue : BasicForms.FrmSupportPrintableComponents
    {
        public FrmBangKeThue()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    case Keys.Delete:
                        DeleteRow();
                        break;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private DataTable _GridDataSouce
        {
            get
            {
                if (gridControl.DataSource is DataTable)
                    return gridControl.DataSource as DataTable;
                else if (gridControl.DataSource is DataView)
                    return (gridControl.DataSource as DataView).ToTable();
                else
                    return null;
            }
        }

        public void InitGridColumnsForPhieuDangKiKham()
        {
            gridControl.DataSource = null;
            gridView.Columns.Clear();

            int visibleIndex = 0;

            DevExpress.XtraGrid.Columns.GridColumn colMa = new DevExpress.XtraGrid.Columns.GridColumn();
            colMa.Caption = "Mã";
            colMa.FieldName = "Ma";
            colMa.Name = "colMa";
            colMa.Visible = true;
            colMa.Width = 90;
            colMa.VisibleIndex = visibleIndex++;
            colMa.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            colMa.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;
            colMa.SummaryItem.DisplayFormat = "Tổng số = {0:### ### ### ###}";

            DevExpress.XtraGrid.Columns.GridColumn colNgay = new DevExpress.XtraGrid.Columns.GridColumn();
            colNgay.Caption = "Ngày đăng kí";
            colNgay.FieldName = "Ngay";
            colNgay.Name = "colNgay";
            colNgay.Visible = true;
            colNgay.Width = 60;
            colNgay.VisibleIndex = visibleIndex++;
            colNgay.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
            colNgay.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo benhNhanInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Ten", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupBenhNhan = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupBenhNhan.Columns.Add(benhNhanInfo);
            repLookupBenhNhan.ValueMember = "ID";
            repLookupBenhNhan.DisplayMember = "Ten";
            repLookupBenhNhan.DataSource = DanhMucBenhNhan.Instance.DataView;

            DevExpress.XtraGrid.Columns.GridColumn colBenhNhan = new DevExpress.XtraGrid.Columns.GridColumn();
            colBenhNhan.Caption = "Bệnh nhân";
            colBenhNhan.FieldName = "BenhNhanID";
            colBenhNhan.Name = "colBenhNhan";
            colBenhNhan.ColumnEdit = repLookupBenhNhan;
            colBenhNhan.Visible = true;
            colBenhNhan.VisibleIndex = visibleIndex++;
            colBenhNhan.Width = 80;
            colBenhNhan.VisibleIndex = visibleIndex++;
            colBenhNhan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colDiaChi = new DevExpress.XtraGrid.Columns.GridColumn();
            colDiaChi.Caption = "Địa chỉ";
            colDiaChi.FieldName = "DiaChi";
            colDiaChi.Name = "colDiaChi";
            colDiaChi.Visible = true;
            colDiaChi.VisibleIndex = visibleIndex++;
            colDiaChi.Width = 80;
            colDiaChi.VisibleIndex = visibleIndex++;
            colDiaChi.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTenCoQuan = new DevExpress.XtraGrid.Columns.GridColumn();
            colTenCoQuan.Caption = "Tên cơ quan";
            colTenCoQuan.FieldName = "TenCoQuan";
            colTenCoQuan.Name = "colTenCoQuan";
            colTenCoQuan.Visible = true;
            colTenCoQuan.Width = 80;
            colTenCoQuan.VisibleIndex = visibleIndex++;
            colTenCoQuan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo bacSiInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FullName", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupBacSi = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupBacSi.Columns.Add(bacSiInfo);
            repLookupBacSi.ValueMember = "ID";
            repLookupBacSi.DisplayMember = "FullName";
            repLookupBacSi.DataSource = UserList.Instance.DataTable.DefaultView;

            DevExpress.XtraGrid.Columns.GridColumn colBacSi = new DevExpress.XtraGrid.Columns.GridColumn();
            colBacSi.Caption = "Bác sĩ";
            colBacSi.FieldName = "BacSiID";
            colBacSi.Name = "colBacSi";
            colBacSi.ColumnEdit = repLookupBacSi;
            colBacSi.Visible = true;
            colBacSi.VisibleIndex = visibleIndex++;
            colBacSi.Width = 80;
            colBacSi.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo ThuNganInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FullName", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupThuNgan = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupThuNgan.Columns.Add(ThuNganInfo);
            repLookupThuNgan.ValueMember = "ID";
            repLookupThuNgan.DisplayMember = "FullName";
            repLookupThuNgan.DataSource = UserList.Instance.DataTable.DefaultView;

            DevExpress.XtraGrid.Columns.GridColumn colThuNgan = new DevExpress.XtraGrid.Columns.GridColumn();
            colThuNgan.Caption = "Người tạo phiếu";
            colThuNgan.FieldName = "ThuNganID";
            colThuNgan.Name = "colThuNgan";
            colThuNgan.ColumnEdit = repLookupThuNgan;
            colThuNgan.Visible = true;
            colThuNgan.VisibleIndex = visibleIndex++;
            colThuNgan.Width = 80;
            colThuNgan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraEditors.Controls.LookUpColumnInfo PhongBanInfo = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Ten", "Tên", 20);
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repLookupPhongBan = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            repLookupPhongBan.Columns.Add(PhongBanInfo);
            repLookupPhongBan.ValueMember = "ID";
            repLookupPhongBan.DisplayMember = "Ten";
            repLookupPhongBan.DataSource = DanhMucDoiTuongNghiepVu.Instance.DataView;

            DevExpress.XtraGrid.Columns.GridColumn colPhongBan = new DevExpress.XtraGrid.Columns.GridColumn();
            colPhongBan.Caption = "Phòng chuyên môn";
            colPhongBan.FieldName = "PhongBanID";
            colPhongBan.Name = "colPhongBan";
            colPhongBan.ColumnEdit = repLookupPhongBan;
            colPhongBan.Visible = true;
            colPhongBan.VisibleIndex = visibleIndex++;
            colPhongBan.Width = 80;
            colPhongBan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTinhTrangBenh = new DevExpress.XtraGrid.Columns.GridColumn();
            colTinhTrangBenh.Caption = "Tình trạng bệnh khi đi khám";
            colTinhTrangBenh.FieldName = "TinhTrangBenh";
            colTinhTrangBenh.Name = "colTinhTrangBenh";
            colTinhTrangBenh.Visible = true;
            colTinhTrangBenh.Width = 100;
            colTinhTrangBenh.VisibleIndex = visibleIndex++;
            colTinhTrangBenh.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colSTTKham = new DevExpress.XtraGrid.Columns.GridColumn();
            colSTTKham.Caption = "STT khám";
            colSTTKham.FieldName = "SoThuTuKham";
            colSTTKham.Name = "colSTTKham";
            colSTTKham.Visible = true;
            colSTTKham.Width = 30;
            colSTTKham.VisibleIndex = visibleIndex++;
            colSTTKham.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTaiKham = new DevExpress.XtraGrid.Columns.GridColumn();
            colTaiKham.Caption = "Tái khám";
            colTaiKham.FieldName = "TaiKham";
            colTaiKham.Name = "colTaiKham";
            colTaiKham.Visible = true;
            colTaiKham.Width = 30;
            colTaiKham.VisibleIndex = visibleIndex++;
            colTaiKham.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colSoTheBHYT = new DevExpress.XtraGrid.Columns.GridColumn();
            colSoTheBHYT.Caption = "Có BHYT";
            colSoTheBHYT.FieldName = "SoTheBHYT";
            colSoTheBHYT.Name = "colSoTheBHYT";
            colSoTheBHYT.Visible = true;
            colSoTheBHYT.Width = 30;
            colSoTheBHYT.VisibleIndex = visibleIndex++;
            colSoTheBHYT.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colTienThanhToan = new DevExpress.XtraGrid.Columns.GridColumn();
            colTienThanhToan.Caption = "Tiền T.toán";
            colTienThanhToan.FieldName = "TienThanhToan";
            colTienThanhToan.Name = "colTienThanhToan";
            colTienThanhToan.Visible = true;
            colTienThanhToan.Width = 50;
            colTienThanhToan.VisibleIndex = visibleIndex++;
            colTienThanhToan.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;
            colTienThanhToan.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            colTienThanhToan.SummaryItem.DisplayFormat = "{0:### ### ### ###}";

            DevExpress.XtraGrid.Columns.GridColumn colGhiChu = new DevExpress.XtraGrid.Columns.GridColumn();
            colGhiChu.Caption = "Ghi chú";
            colGhiChu.FieldName = "GhiChu";
            colGhiChu.Name = "colGhiChu";
            colGhiChu.Visible = true;
            colGhiChu.Width = 60;
            colGhiChu.VisibleIndex = visibleIndex++;
            colGhiChu.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colDaThuTien = new DevExpress.XtraGrid.Columns.GridColumn();
            colDaThuTien.Caption = "Đã thu tiền";
            colDaThuTien.FieldName = "DaThuTien";
            colDaThuTien.Name = "colDaThuTien";
            colDaThuTien.Visible = true;
            colDaThuTien.Width = 30;
            colDaThuTien.VisibleIndex = visibleIndex++;
            colDaThuTien.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            DevExpress.XtraGrid.Columns.GridColumn colDaXuLy = new DevExpress.XtraGrid.Columns.GridColumn();
            colDaXuLy.Caption = "Đã xử lý";
            colDaXuLy.FieldName = "DaXuLy";
            colDaXuLy.Name = "colDaXuLy";
            colDaXuLy.Visible = true;
            colDaXuLy.Width = 30;
            colDaXuLy.VisibleIndex = visibleIndex++;
            colDaXuLy.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.DisplayText;

            this.gridView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
                colMa, colNgay, colBenhNhan, colDiaChi, colTenCoQuan, colBacSi, colPhongBan, colThuNgan, colTinhTrangBenh,
                colTaiKham, colSoTheBHYT, colTienThanhToan, colGhiChu, colDaThuTien, colDaXuLy });

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            }
        }

        public void FormatGridViewForCopyCell(DevExpress.XtraGrid.Views.Grid.GridView gridView)
        {
            try
            {
                gridView.OptionsBehavior.Editable = true;
                gridView.OptionsBehavior.ReadOnly = true;
            }
            catch (Exception ex)
            {
            }
        }

        private void FrmBangKeThue_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKyBaoCao.SelectedText = "Hôm nay";

                InitGridColumnsForPhieuDangKiKham();

                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                    column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                }

                FormatGridViewForCopyCell(gridView); //KCB thì cho copy trong các report
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void gridView_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void DeleteRow()
        {
            try
            {
                if (gridView == null || gridView.SelectedRowsCount == 0) return;

                DataRow[] rows = new DataRow[gridView.SelectedRowsCount];

                for (int i = 0; i < gridView.SelectedRowsCount; i++)
                    rows[i] = gridView.GetDataRow(gridView.GetSelectedRows()[i]);

                foreach (DataRow row in rows)
                    row.Delete();
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            string kyBaoCao = cmbKyBaoCao.Text;
            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                //lấy không có thẻ BHYT
                string BHYTCondition = string.Format("(SoTheBHYT = '' OR SoTheBHYT IS NULL)");
                //Loại những bệnh nhân gắn với cơ quan, tức lấy những bệnh nhân trường cơ quan không có giá trị
                string coQuanCondition = string.Format("(D.ID = '00000000-0000-0000-0000-000000000000' OR D.ID IS NULL)");

                cmd.CommandText = string.Format("SELECT A.*, B. Ten TenBenhNhan, B.DiaChi, N'Khám bệnh' DienGiai, \n" +
                                                "   D.ID CoQuanTheoBenhNhanID, D.Ten TenCoQuan \n" +
                                                "FROM Clinic_Phieu A INNER JOIN Clinic_BenhNhan B ON A.BenhNhanID = B.ID \n" +
                                                "   LEFT JOIN Clinic_DichVu C ON C.ID = A.DichVuID \n" +
                                                "   LEFT JOIN Clinic_CoQuan D ON D.ID = B.CoQuanID  \n" +
                                                "WHERE {0} AND {1} \n" +
                                                "	AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n",
                                                BHYTCondition, coQuanCondition);

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                //Báo cáo động --> k cần tạo dataset làm gì cho mất công
                DataTable dt = new DataTable();
                da.Fill(dt);

                gridControl.DataSource = dt;

                FormatNumberInGridView(gridView);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                string option1 = string.Format("Từ {0}:{1} ngày {2}/{3}/{4} đến {5}:{6} ngày {7}/{8}/{9}",
                                dtNgayBatDau.DateTime.Hour, dtNgayBatDau.DateTime.Minute,
                                dtNgayBatDau.DateTime.Day, dtNgayBatDau.DateTime.Month, dtNgayBatDau.DateTime.Year,
                                dtNgayKetThuc.DateTime.Hour, dtNgayKetThuc.DateTime.Minute,
                                dtNgayKetThuc.DateTime.Day, dtNgayKetThuc.DateTime.Month, dtNgayKetThuc.DateTime.Year);
                string option2 = "";

                gridView.OptionsPrint.MaxMergedCellHeight = -1;  //Để in ra cũng merge cell y như gridcontrol
                PrintWithHeaderAndFooter(true, gridControl, true, true, "BẢNG KÊ THU TIỀN KHÁM BỆNH (LÀM THUẾ) - BỆNH NHÂN KHÔNG CÓ BHYT", option1, option2, "", "");
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                PrintClinic print = new PrintClinic();
                if (_GridDataSouce != null)
                    print.PrintBangKeThue(_GridDataSouce, dtNgayKetThuc.DateTime);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
    }
}
